package com.bsh.utils.system;

import com.bsh.utils.SimpleCache;

/**
 * 账户锁
 * 
 * @author gsh
 *
 */
public class AccountLock {
	private static SimpleCache<Integer> cache = new SimpleCache<Integer>(10);

	/**
	 * 取得锁
	 * true 未锁-可用， false 别的地方已锁-不可用
	 * @param accountId
	 * @param userId
	 * @return
	 */
	public static boolean getLock(int accountId, int userId) {
		String key = String.format("%s_%s", accountId, userId);
		if (cache.Get(key,Integer.class)!=null && cache.Get(key,Integer.class) == 1)
			return false;
		cache.Put(key, 1);
		return true;
	}

	/**
	 * 解锁
	 * 
	 * @param accountId
	 * @param userId
	 * @return
	 */
	public static void unLock(int accountId, int userId) {
		String key = String.format("%s_%s", accountId, userId);
		cache.Put(key, 0);
	}

	
	/**
	 * 查询锁的状态
	 * true 是已锁定， false 是未锁-可用
	 * @param accountId
	 * @param userId
	 * @return
	 */
	public static boolean getLockStatus(int accountId, int userId) {
		String key = String.format("%s_%s", accountId, userId);
		Object obj=cache.Get(key);
		if(obj==null)return false;
		return cache.Get(key) == 1;
	}
	
	public static void main(String[] args) {
		boolean lock = AccountLock.getLock(1, 2);
		System.out.println(lock);

		lock = AccountLock.getLock(1, 2);
		System.out.println(lock);
		
		AccountLock.unLock(1, 2);
		
		lock = AccountLock.getLock(1, 2);
		System.out.println(lock);
		
		
	}
}
